package com.test.sdk.provider.exception;

import com.test.sdk.provider.util.ErrorConstants;
import com.test.sdk.provider.util.JsonUtil;
import com.test.sdk.provider.util.ResponseTO;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class SdkExceptionHandler implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
        e.printStackTrace();
        ResponseTO responseTO = new ResponseTO(false, null);
        if (e instanceof SdkException) {//捕获的自定义异常
            responseTO.setError(((SdkException) e).getErrorCodeTO());
        } else {//未知异常
            responseTO.setError(ErrorConstants.UNKOWN_ERROR);
        }
        MappingJackson2JsonView view = new MappingJackson2JsonView();
        view.setExtractValueFromSingleKeyModel(true);
        return new ModelAndView(view, "response", responseTO);
    }

    public static void handlerException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Exception e) {
        httpServletResponse.setCharacterEncoding("utf-8");
        httpServletResponse.setHeader("Cache-Control", "no-cache");
        httpServletResponse.setContentType("application/json; charset=UTF-8");
        ResponseTO responseTO = new ResponseTO(false, null);
        if (e instanceof SdkException) {//捕获的自定义异常
            responseTO.setError(((SdkException) e).getErrorCodeTO());
        } else {//未知异常
            responseTO.setError(ErrorConstants.UNKOWN_ERROR);
        }
        try {
            PrintWriter writer =httpServletResponse.getWriter();
            writer.write(JsonUtil.getJSON(responseTO));
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }
}
